import AntDesign from "@expo/vector-icons/AntDesign";
import {
  convertToAffineMatrix,
  convertToColumnMajor,
  Matrix4,
  multiply4,
  processTransform3d,
  translate,
} from "@shopify/react-native-skia";
import { useEffect } from "react";
import { Platform, View } from "react-native";
import { Gesture, GestureDetector } from "react-native-gesture-handler";
import Animated, {
  type SharedValue,
  useAnimatedStyle,
  useDerivedValue,
  useSharedValue,
} from "react-native-reanimated";

const multiply = (...matrices: Matrix4[]) => {
  "worklet";
  return matrices.reduce((acc, matrix) => multiply4(acc, matrix), Matrix4());
};

// 元素尺寸接口
interface ElementDimensions {
  width: number;
  height: number;
  x: number;
  y: number;
}

// 手势层属性接口
interface UniversalGestureHandlerProps {
  matrix: SharedValue<Matrix4>;
  size: ElementDimensions;
  debug?: boolean;
  rotation?: number; // 旋转角度
  scale?: number; // 缩放比例
  zIndex?: number; // 层级
  // 使用 SharedValue 来触发 JS 线程的回调
  selectSignal?: SharedValue<{ layerId: string; timestamp: number } | null>;
  deleteSignal?: SharedValue<{ layerId: string; timestamp: number } | null>;
  editSignal?: SharedValue<{ layerId: string; timestamp: number } | null>;
  // 变换信号
  transformSignal?: SharedValue<{
    layerId: string;
    x?: number;
    y?: number;
    rotation?: number;
    scale?: number;
    timestamp: number;
  } | null>;
  // 图层ID，用于识别是哪个图层被操作
  layerId?: string;
  // 图片信息，用于对比
  imageInfo?: {
    x: number;
    y: number;
    width: number;
    height: number;
    originalWidth: number;
    originalHeight: number;
  };
}

export const UniversalGestureHandler = ({
  matrix,
  size,
  debug = false,
  rotation = 0,
  scale = 1,
  zIndex = 4,
  selectSignal,
  deleteSignal,
  editSignal,
  transformSignal,
  layerId,
  imageInfo,
}: UniversalGestureHandlerProps) => {
  // 变换状态 - 使用图片的初始位置作为基准
  const currentPosition = useSharedValue({ x: 0, y: 0 });
  const previousPosition = useSharedValue({ x: 0, y: 0 });

  const currentRotation = useSharedValue(rotation);
  const previousRotation = useSharedValue(rotation);

  const currentScale = useSharedValue(scale);
  const previousScale = useSharedValue(scale);

  // 初始化时设置正确的值 - 只在组件挂载时执行
  useEffect(() => {
    console.log("UniversalGestureHandler 初始化:", {
      layerId,
      size,
      scale,
      rotation,
      initialPosition: { x: 0, y: 0 },
    });

    // 设置初始位置偏移量
    currentPosition.value = { x: 0, y: 0 };
    previousPosition.value = { x: 0, y: 0 };

    currentScale.value = scale;
    previousScale.value = scale;
    currentRotation.value = rotation;
    previousRotation.value = rotation;
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [scale, rotation]); // 依赖外部传入的scale和rotation

  // 拖拽手势 - 修正累积计算
  const pan = Gesture.Pan()
    .onStart(() => {
      "worklet";
      console.log(
        "Pan STARTED for layerId:",
        layerId,
        "previousPosition:",
        previousPosition.value
      );
    })
    .onChange((e) => {
      "worklet";
      currentPosition.value = {
        x: e.translationX + previousPosition.value.x,
        y: e.translationY + previousPosition.value.y,
      };

      // 在拖拽过程中实时发送变换信号
      if (transformSignal && layerId) {
        transformSignal.value = {
          layerId,
          x: size.x + currentPosition.value.x,
          y: size.y + currentPosition.value.y,
          timestamp: Date.now(),
        };
      }
    })
    .onEnd(() => {
      "worklet";
      console.log(
        "Pan ended for layerId:",
        layerId,
        "final position:",
        currentPosition.value
      );
      previousPosition.value = currentPosition.value;
      // 发送选中信号
      if (selectSignal && layerId) {
        selectSignal.value = { layerId, timestamp: Date.now() };
        console.log("Sent select signal for layerId:", layerId);
      }
    });

  // 缩放手势 - 完全参考 drawingCanvas 的实现
  const pinch = Gesture.Pinch()
    .onStart(() => {
      "worklet";
      console.log("Pinch STARTED for layerId:", layerId);
    })
    .onChange((e) => {
      "worklet";
      currentScale.value = e.scale * previousScale.value;

      // 在缩放过程中实时发送变换信号
      if (transformSignal && layerId) {
        transformSignal.value = {
          layerId,
          scale: currentScale.value,
          x: size.x + currentPosition.value.x,
          y: size.y + currentPosition.value.y,
          timestamp: Date.now(),
        };
      }
    })
    .onEnd(() => {
      "worklet";
      console.log("Pinch ended, final scale:", currentScale.value);
      previousScale.value = currentScale.value;

      // 发送选中信号
      if (selectSignal && layerId) {
        selectSignal.value = { layerId, timestamp: Date.now() };
        console.log("Sent select signal for layerId:", layerId);
      }
    });

  // 旋转手势 - 完全参考 drawingCanvas 的实现
  const rotate = Gesture.Rotation()
    .onStart(() => {
      "worklet";
      console.log("Rotation STARTED for layerId:", layerId);
    })
    .onChange((e) => {
      "worklet";
      currentRotation.value = e.rotation + previousRotation.value;
      // 在旋转过程中实时发送变换信号
      if (transformSignal && layerId) {
        transformSignal.value = {
          layerId,
          rotation: currentRotation.value * (180 / Math.PI),
          scale: currentScale.value,
          x: size.x + currentPosition.value.x,
          y: size.y + currentPosition.value.y,
          timestamp: Date.now(),
        };
      }
    })
    .onEnd(() => {
      "worklet";
      console.log("Rotation ended for layerId:", layerId);
      previousRotation.value = currentRotation.value;

      // 发送选中信号
      if (selectSignal && layerId) {
        selectSignal.value = { layerId, timestamp: Date.now() };
        console.log("Sent select signal for layerId:", layerId);
      }
    });

  // 组合手势 - 使用简单的方式
  const gesture = Gesture.Simultaneous(pan, rotate, pinch);

  // 按钮拖拽手势 - 先判断操作类型，再执行相应逻辑
  const buttonPan = Gesture.Pan()
    .onStart(() => {
      "worklet";
      console.log("Button Pan STARTED for layerId:", layerId);
      // 记录手势开始时的状态作为基准
    })
    .onChange((e) => {
      "worklet";
      // 获取拖动的位移差
      const deltaX = e.translationX;
      const deltaY = e.translationY;
      console.log("记录手势开始时的状态作为基准记录手势开始时的状态作为基准:", e);
      // 计算拖动的总距离
      const dragDistance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);

      // 最小拖动距离阈值，避免误操作
      if (dragDistance < 10) return;

      // 计算拖动角度（弧度）
      const dragAngle = Math.atan2(deltaY, deltaX);
      const dragAngleDegrees = dragAngle * (180 / Math.PI);

      // 判断操作类型
      let operationType = "未知";
      let isScale = false;
      let isRotate = false;

      // 暂时只做缩放，所有拖动都执行缩放操作
      operationType = "缩放操作";
      isScale = true;
      isRotate = false; // 暂时关闭旋转

      // 打印操作信息
      console.log("按钮拖拽分析:", {
        deltaX,
        deltaY,
        dragDistance,
        dragAngleDegrees: dragAngleDegrees.toFixed(1) + "°",
        operationType,
        isScale,
        isRotate,
      });

      // 执行相应的操作
      if (isScale) {
        // 缩放操作
        const scaleDirection = deltaX > 0 ? 1 : -1; // 向右放大，向左缩小
        const scaleRatio = 0.005;
        const scaleChange = dragDistance * scaleRatio * scaleDirection;
        const newScale = previousScale.value * (1 + scaleChange);
        currentScale.value = Math.max(0.1, Math.min(5, newScale));

        console.log("缩放执行:", {
          scaleDirection,
          scaleChange: scaleChange.toFixed(4),
          newScale: currentScale.value.toFixed(3),
        });
      }

      // 暂时注释掉旋转功能
      // if (isRotate) {
      //   // 旋转操作 - 基于手势角度判断旋转方向
      //   const rotateRatio = 0.04; // 旋转灵敏度

      //   // 计算手势的旋转方向
      //   // 手势角度为正（0-180°）时，顺时针旋转
      //   // 手势角度为负（-180°-0°）时，逆时针旋转
      //   let rotateDirection = 1; // 默认顺时针

      //   if (dragAngleDegrees > 0) {
      //     // 手势角度为正，顺时针旋转
      //     rotateDirection = 1;
      //   } else if (dragAngleDegrees < 0) {
      //     // 手势角度为负，逆时针旋转
      //     rotateDirection = -1;
      //   }

      //   // 基于拖动距离计算旋转角度
      //   const rotationChange = dragDistance * rotateRatio * rotateDirection;
      //   const newRotation = previousRotation.value + rotationChange;
      //   currentRotation.value = newRotation;

      //   console.log("旋转执行:", {
      //     dragAngleDegrees: dragAngleDegrees.toFixed(1) + "°",
      //     rotateDirection,
      //     rotationChange: rotationChange.toFixed(4),
      //     newRotation: currentRotation.value.toFixed(3),
      //     rotationDirection: rotateDirection > 0 ? "顺时针" : "逆时针"
      //   });
      // }

      // 发送变换信号
      if (transformSignal && layerId) {
        transformSignal.value = {
          layerId,
          scale: currentScale.value,
          rotation: currentRotation.value * (180 / Math.PI),
          x: size.x + currentPosition.value.x,
          y: size.y + currentPosition.value.y,
          timestamp: Date.now(),
        };
      }
    })
    .onEnd(() => {
      "worklet";
      console.log("Button Pan ended for layerId:", layerId);
      // 更新previous值，为下次手势做准备
      previousScale.value = currentScale.value;
      previousRotation.value = currentRotation.value;
    });

  // 计算变换矩阵 - 使用与 drawingCanvas 一致的变换序列
  const newMatrix = useDerivedValue(() => {
    return processTransform3d([
      { translateX: currentPosition.value.x },
      { translateY: currentPosition.value.y },
      { translateX: size.width / 2 },
      { translateY: size.height / 2 },
      { scale: currentScale.value },
      { rotateZ: currentRotation.value },
      { translateX: -size.width / 2 },
      { translateY: -size.height / 2 },
    ]);
  });

  useDerivedValue(() => {
    matrix.value = newMatrix.value;
  });

  // 手势层样式 - 使用与 drawingCanvas 一致的样式计算
  const style = useAnimatedStyle(() => {
    const m = multiply(
      translate(-size.width / 2, -size.height / 2),
      newMatrix.value,
      translate(size.width / 2, size.height / 2)
    );

    const m4 = convertToColumnMajor(m);

    return {
      position: "absolute",
      width: size.width,
      height: size.height,
      top: size.y,
      left: size.x,
      zIndex: zIndex,
      backgroundColor: debug ? "rgba(255, 0, 0, 0.3)" : "transparent", // 调试模式下显示半透明红色
      pointerEvents: "auto" as const,
      transform: [
        {
          matrix:
            Platform.OS === "web"
              ? convertToAffineMatrix(m4)
              : (m4 as unknown as number[]),
        },
      ],
    };
  });

  return (
    <Animated.View style={style}>
      {/* 手势检测层 */}
      <GestureDetector gesture={gesture}>
        <View style={{ width: "100%", height: "100%" }} />
      </GestureDetector>
      {/* 按钮  */}
      <GestureDetector gesture={buttonPan}>
        <Animated.View
          style={useAnimatedStyle(() => ({
            position: "absolute" as const,
            top: -12,
            right: -12,
            width: 24,
            height: 24,
            backgroundColor: "rgba(165, 248, 11, 1)",
            borderRadius: 12,
            justifyContent: "center",
            alignItems: "center",
            zIndex: zIndex + 1,
            // 防止按钮跟随父容器缩放
            transform: [{ scale: 1 / currentScale.value }],
          }))}
        >
          <AntDesign name="arrowsalt" size={14} color="#fff" />
        </Animated.View>
      </GestureDetector>
    </Animated.View>
  );
};
